import _axios from "~/common/axios";

type CommonAction = {
  save: (payload: any) => Promise<any>;
  update: (payload: any) => Promise<any>;
  findPage: (payload: any) => Promise<any>;
  findOne: (payload: any) => Promise<any>;
  deleteOne: (payload: any) => Promise<any>;
  deleteMul: (payload: any) => Promise<any>;
  findList: (payload: any) => Promise<any>;
};

export function createCommonActions(root: string): CommonAction {
  return {
    save(payload: any) {
      return new Promise((resolve, reject) => {
        _axios
          .POST({
            url: `/${root}/save`,
            data: payload,
          })
          .then((res) => {
            resolve(res);
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    update(payload: any) {
      return new Promise((resolve, reject) => {
        _axios
          .POST({
            url: `/${root}/update`,
            data: payload,
          })
          .then((res) => {
            resolve(res);
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    findPage(payload: any) {
      return new Promise((resolve, reject) => {
        _axios
          .POST({
            url: `/${root}/find/page`,
            data: payload,
          })
          .then((res) => {
            resolve(res);
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    findOne(id: string) {
      return new Promise((resolve, reject) => {
        _axios
          .GET({
            url: `/${root}/find/` + id,
            data: {},
          })
          .then((res) => {
            resolve(res);
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    deleteOne(id: string) {
      return new Promise((resolve, reject) => {
        _axios
          .GET({
            url: `/${root}/delete/` + id,
            data: {},
          })
          .then((res) => {
            resolve(res);
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    deleteMul(id: string) {
      return new Promise((resolve, reject) => {
        _axios
          .POST({
            url: `/${root}/delete/ids`,
            data: { id: id },
          })
          .then((res) => {
            resolve(res);
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    findList(payload: any) {
      return new Promise((resolve, reject) => {
        _axios
          .POST({
            url: `/${root}/find/list`,
            data: payload,
          })
          .then((res) => {
            resolve(res);
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
  };
}
